# -*- coding: cp1252 -*-

import os

import wx
import wx.grid
import wx.lib.printout as  printout
import get_appdata_folder
#import do_plotting
import do_plotting_pdf

help_path = os.getcwd()
appdata_path = get_appdata_folder.get_appdata_directory()

wildcard_fasta = "Fasta files (*.fasta)|*.fasta|"     \
           "All files (*.*)|*.*"

class MakeGrid(wx.Frame):
    """Frame for the Grid."""
    def __init__(self, data, nr):
        wx.Frame.__init__(self, None, title = "Results",
                        size = (700, (nr*70)+150))
        wx.CallAfter(self.SetFocus)
        self.nr = nr
        self.ids = []
        for id in data:
            self.ids.append(id[0])

        p = wx.Panel(self, -1)
        self.grid = wx.grid.Grid(p, size = (500, 500))

        self.grid.CreateGrid(len(data), len(data[0]))
        bs = wx.BoxSizer(wx.VERTICAL)
        bs.Add(self.grid, 1, wx.GROW|wx.ALL, 5)
        p.SetSizer(bs)

        for row in range(len(data)):
            for col in range(len(data[0])):
                self.grid.SetCellValue(row, col, str(data[row][col]))


        # Append one Checkbox col and set frist 5 = True
        self.grid.AppendCols(1)
        attr = wx.grid.GridCellAttr()
        attr.SetEditor(wx.grid.GridCellBoolEditor())
        attr.SetRenderer(wx.grid.GridCellBoolRenderer())
        self.grid.SetColAttr(3, attr)
        self.len_data = len(data)
        if self.len_data < 5:
            displ = self.len_data
        else:
            displ = 5
        for i in range(displ):
            self.grid.SetCellValue(i, 3, str(1))

        # Make checkbox
        self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK,self.onMouse)
        self.Bind(wx.grid.EVT_GRID_SELECT_CELL,self.onCellSelected)
        self.Bind(wx.grid.EVT_GRID_EDITOR_CREATED, self.onEditorCreated)

        self.grid.SetDefaultRowSize(55, True)
        self.grid.SetColSize(0, 200)
        self.grid.SetColSize(1, 100)
        self.grid.SetColSize(2, 100)
        self.grid.SetColSize(3, 200)

        self.grid.SetColLabelValue(0, "Query Name")
        self.grid.SetColLabelValue(1, "All Hits")
        self.grid.SetColLabelValue(2, "Efficent Hits")
        self.grid.SetColLabelValue(3, "Display on graphic")

        face = 'Courier New'
        self.grid.SetDefaultCellFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False, face))

        # Create Toolbar
        self.toolbar()
        self.data = data

    def onMouse(self,evt):
        if evt.Col == 3:
            wx.CallLater(100,self.toggleCheckBox)
        evt.Skip()

    def toggleCheckBox(self):
        self.cb.Value = not self.cb.Value
        self.afterCheckBox(self.cb.Value)

    def onCellSelected(self,evt):
        if evt.Col == 3:
            wx.CallAfter(self.grid.EnableCellEditControl)
        evt.Skip()

    def onEditorCreated(self,evt):
        if evt.Col == 3:
            self.cb = evt.Control
            self.cb.WindowStyle |= wx.WANTS_CHARS
            self.cb.Bind(wx.EVT_KEY_DOWN,self.onKeyDown)
            self.cb.Bind(wx.EVT_CHECKBOX,self.onCheckBox)
        evt.Skip()

    def onKeyDown(self,evt):
        if evt.KeyCode == wx.WXK_UP:
            if self.GridCursorRow > 0:
                self.DisableCellEditControl()
                self.MoveCursorUp(False)
        elif evt.KeyCode == wx.WXK_DOWN:
            if self.GridCursorRow < (self.NumberRows-1):
                self.DisableCellEditControl()
                self.MoveCursorDown(False)
        elif evt.KeyCode == wx.WXK_LEFT:
            if self.GridCursorCol > 0:
                self.DisableCellEditControl()
                self.MoveCursorLeft(False)
        elif evt.KeyCode == wx.WXK_RIGHT:
            if self.GridCursorCol < (self.NumberCols-1):
                self.DisableCellEditControl()
                self.MoveCursorRight(False)
        else:
            evt.Skip()

    def onCheckBox(self,evt):
        self.afterCheckBox(evt.IsChecked())

    def afterCheckBox(self,isChecked):
        self.grid.SetCellValue(self.grid.GridCursorRow, 3, ["", "1"][isChecked])


    def toolbar(self):
        toolbar = self.CreateToolBar()
        toolbar.SetBackgroundColour(wx.Colour(222, 233, 246, 255))
        toolbar.SetToolBitmapSize((40, 40))
        # bmps
        chart_bmp = wx.Bitmap(help_path + "\\images\\chart.png", wx.BITMAP_TYPE_PNG)
        #export_bmp = wx.Bitmap(help_path + "\\images\\export.png", wx.BITMAP_TYPE_PNG)
        check_empty_bmp = wx.Bitmap(help_path + "\\images\\checkbox_empty.png", wx.BITMAP_TYPE_PNG)
        check_full_bmp = wx.Bitmap(help_path + "\\images\\checkbox_full.png", wx.BITMAP_TYPE_PNG)
        copy_bmp = wx.Bitmap(help_path + "\\images\\clipboard_edit.png", wx.BITMAP_TYPE_PNG)
        print_bmp = wx.Bitmap(help_path + "\\images\\print.png", wx.BITMAP_TYPE_PNG)

        toolbar.AddSimpleTool(0, check_full_bmp, 'Chek all', '')
        toolbar.AddSimpleTool(1, check_empty_bmp, 'Uncheck all', '')
        toolbar.AddSeparator()
        toolbar.AddSimpleTool(2, chart_bmp, 'Show chart', '')
        toolbar.AddSeparator()
        #toolbar.AddSimpleTool(3, export_bmp, 'Save as...', '')
        toolbar.AddSimpleTool(4, copy_bmp, 'Copy table to clipboard', '')
        toolbar.AddSimpleTool(5, print_bmp, 'Print table', '')


        self.Bind(wx.EVT_TOOL, self.check_all, id=0)
        self.Bind(wx.EVT_TOOL, self.uncheck_all, id=1)
        self.Bind(wx.EVT_TOOL, self.draw_line_chart, id=2)
        self.Bind(wx.EVT_TOOL, self.to_clipboard, id=4)
        self.Bind(wx.EVT_TOOL, self.printout, id=5)

        toolbar.Realize()

    def check_all(self, evt):
        for i in range(self.len_data):
            self.grid.SetCellValue(i, 3, str(1))

    def uncheck_all(self, evt):
        for i in range(self.len_data):
            self.grid.SetCellValue(i, 3, str(0))


    def printout(self, evt):
        """Print."""
        frame = wx.Frame(None, -1, "Printout" , pos=(50,50), size=(200,100),
                        style=wx.DEFAULT_FRAME_STYLE, name="Printout")
        data = self.data
        TablePanel(self, frame, data)

    def export_sirna_seq(self, evt):
        """Export all siRNA sequences."""
        dlg = wx.FileDialog(
            self, message="Save file as ...", defaultDir=os.getcwd(),
            defaultFile="si-Fi_results", wildcard=wildcard_fasta, style=wx.SAVE
            )
        dlg.SetFilterIndex(2)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            try:
                os.rename(appdata_path + '\\files\\siRNA_seq_results.txt', str(path))
            except WindowsError:
                os.remove(path)
                os.rename(appdata_path + '\\files\\siRNA_seq_results.txt', str(path))
            dlg2 = wx.MessageDialog(self, 'siRNA sequences saved!',
                           'Saved',
                           wx.OK | wx.ICON_INFORMATION)
            dlg2.ShowModal()
            dlg2.Destroy()
        dlg.Destroy()

    def to_clipboard(self, evt):
        """Copy to clipboard."""
        f = open(appdata_path + "\\files\\data_hits.txt", "r")
        msg = 'Id' + '\t' + 'All Hits' + '\t' 'Eff Hits' + '\n' + f.read()
        f.close()
        data = wx.TextDataObject()
        data.SetText(msg)
        if wx.TheClipboard.Open():
            wx.TheClipboard.SetData(data)
            wx.TheClipboard.Flush()
            wx.TheClipboard.Close()

    def draw_line_chart(self, evt):
        """Draw line chart."""
        #Draw only checked graphs
        checked_id = []
        for i in range(self.len_data):
            checked = self.grid.GetCellValue(i, 3)
            id = self.grid.GetCellValue(i, 0)
            if checked == "1":
                checked_id.append(self.ids[i])

        app = wx.PySimpleApp()
        frame = do_plotting_pdf.PlottingFrame(ids = checked_id)
        frame.Show(True)
        app.MainLoop()
#===============================================================================
class TablePanel(wx.Panel):
    def __init__(self, parent, frame, data):
        """Frame to print table."""
        wx.Panel.__init__(self, parent, -1)
        self.frame = frame
        self.data = data
        self.PreviewLine()

    def PreviewLine(self):
        """Preview."""
        prt = printout.PrintTable(self.frame)
        prt.label = ["Query Name", "All Hits", "Efficient Hits"]
        prt.set_column = [2, 1.4, 1.4]
        #prt.SetLandscape()
        prt.SetHeader(align=wx.ALIGN_CENTRE)
        prt.data = self.data
        prt.SetFooter()
        prt.Preview()